package scms.feign.config;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.cloud.openfeign.FeignClientProperties;
import org.springframework.cloud.openfeign.FeignClientProperties.FeignClientConfiguration;
import org.springframework.context.annotation.Configuration;

@Configuration
@ConditionalOnClass(FeignClientProperties.class)
public class FeignRequestTokenConfiguration implements InitializingBean{

	@Autowired
	private FeignClientProperties feignClientProperties;

	@Override
	public void afterPropertiesSet() throws Exception {
		Map<String, FeignClientConfiguration> config = feignClientProperties.getConfig();
		FeignClientConfiguration defConfig =  config.get(feignClientProperties.getDefaultConfig());
		if(defConfig == null){
			defConfig = new FeignClientConfiguration();
			config.put(feignClientProperties.getDefaultConfig(), defConfig);
		}
		List requestInterceptors = defConfig.getRequestInterceptors();
		if(requestInterceptors == null){
			requestInterceptors = new ArrayList<>();
			defConfig.setRequestInterceptors(requestInterceptors);
		}
		requestInterceptors.add(FeignTokenRequestInterceptor.class);
	}
}
